# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp import tools
from openerp.osv import fields, osv

class order_card_report(osv.osv):
    _name = "order.card.report"
    _description = u"卡券订单明细统计"
    _auto = False

    _columns = {
        'partner_id': fields.many2one('res.partner', u'客户', readonly=True),
        'shipped_date': fields.date(u'发货日期', readonly=True),
        'order_name': fields.char(u'订单', readonly=True),
        'product_id': fields.many2one('product.product', u'产品', readonly=True),
        'is_shipped': fields.boolean(u'是否发货', readonly=True),
        'is_active': fields.boolean(u'是否激活', readonly=True),
        'is_return': fields.boolean(u'是否退货', readonly=True),
        'quantity': fields.integer(u'数量', readonly=True),
        'amount': fields.float(u'金额', readonly=True)
    }

    #建立视图
    def init(self, cr):
        tools.drop_view_if_exists(cr, self._table)
        cr.execute("""CREATE or REPLACE VIEW %s as (
            SELECT min(oc.id) as id,
                so.partner_id,
                DATE(oc.shipped_date) as shipped_date,
                so.name as order_name,
                oc.product_id,
                oc.is_shipped,
                oc.is_active,
                so.is_return,
                SUM(CASE WHEN so.is_return THEN 0 - oc.continue_number ELSE oc.continue_number END) as quantity,
                SUM(oc.amount) as amount
            FROM sale_order so
            INNER JOIN order_card oc ON so.id=oc.order_id
            GROUP BY oc.shipped_date, so.partner_id, so.name, oc.product_id, oc.is_shipped, oc.is_active, so.is_return)
            """ % (self._table,))
